package com.chujian.Activities;

import java.util.List;

import com.chujian.Adapter.OrderCurrentListAdapter;
import com.chujian.Global.Global;
import com.chujian.Threads.HttpClientPostThread;
import com.chujian.Threads.HttpClientGetThread;
import com.chujian.Utils.Constan;
import com.chujian.Utils.JsonUtil;
import com.chujian.Utils.Util;
import com.chujian.model.FoodList;
import com.chujian.model.Order;
import com.chujian.orderingsystem.R;
import com.google.gson.Gson;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ListView;

public class OrderCurrentListActivityConsumer extends Activity implements OnItemClickListener,OnItemLongClickListener{
	private ListView mListView;
	private OrderCurrentListAdapter mAdapter;
	private List<Order> mList;
	private int cancelPosition;
	private String tableName;
	private int tablePosition=-1;
	private Handler mHandler=new Handler(){
		public void handleMessage(android.os.Message msg) {
			super.handleMessage(msg);
			String str=(String) msg.obj;
			
			if(str!=null){
				if(str.equals("cancelRequestSuccess")){
//					Toast.makeText(OrderCurrentListActivityConsumer.this, "订单取消成功", Toast.LENGTH_SHORT).show();
//					mList.remove(cancelPosition);
//					mAdapter.notifyDataSetChanged();
					Util.confirmDialog("提示", "订单取消请求已经通知到店家，请等待店家确认...", OrderCurrentListActivityConsumer.this);
				}else if(str.equals("cancelRequestFailed")){
//					Toast.makeText(OrderCurrentListActivityConsumer.this, "订单取消失败", Toast.LENGTH_SHORT).show();
					Util.confirmDialog("警告", "订单取消请求失败！", OrderCurrentListActivityConsumer.this);
				}else if(str.equals("changeTableSuccess")){
					mList.get(tablePosition).setTableName(tableName);
					mAdapter.notifyDataSetChanged();
					Util.confirmDialog("提示", "餐桌修改成功！", OrderCurrentListActivityConsumer.this);
				}else if(str.equals("changeTableFailed")){
					Util.confirmDialog("警告", "餐桌修改失败！", OrderCurrentListActivityConsumer.this);
				}
				else{
					Log.i("OrderCurrentListActivityConsumer", str);
					mList=JsonUtil.OrderListFromJson(str);
					mAdapter=new OrderCurrentListAdapter(OrderCurrentListActivityConsumer.this,mList);
					mListView.setAdapter(mAdapter);
					
				}
				
			}
		};
	};
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.order_current_list);
		mListView=(ListView) findViewById(R.id.lv_order_current_list);
		mListView.setOnItemClickListener(this);
		mListView.setOnItemLongClickListener(this);
		String userPhone=Global.loginUser.getUserPhone();
		String url=Constan.BASE_URL+"OrderCurrentListServletConsumer"+"?userPhone="+userPhone+"&orderStatus="+0;
		new HttpClientGetThread(url,mHandler).start();;
	}
	/**
	 * 返回按钮监听
	 * @param v
	 */
	public void IbBack(View v){
		OrderCurrentListActivityConsumer.this.finish();
	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if(requestCode==1000&&resultCode==1001){
			String orderJson=data.getStringExtra("order_json");
			int position=data.getIntExtra("modifyPosition", -1);
			Order order=JsonUtil.OrderFromJson(orderJson);
			mList.get(position).setTotalPrice(order.getTotalPrice());
			mList.get(position).setFoodList(order.getFoodList());
			mAdapter.notifyDataSetChanged();
		}else if(requestCode==1000&&resultCode==3003){
			String OrderMofify=data.getStringExtra("newAddOrder");
			int position=data.getIntExtra("modifyPosition", -1);
			Order order=JsonUtil.OrderFromJson(OrderMofify);
			mList.get(position).setTotalPrice(order.getTotalPrice()+mList.get(position).getTotalPrice());
			for(FoodList f:order.getFoodList()){
				mList.get(position).getFoodList().add(f);
			}
			mAdapter.notifyDataSetChanged();
		}
		if(resultCode==1002&&requestCode==1000){
			tableName=data.getStringExtra("tableName");
			changeTableDialog(tablePosition, tableName);
		}
	}
	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
//		Bundle bundle=new Bundle();
//		bundle.putSerializable("currentOrder", mList.get(position));
		Intent intent=new Intent(OrderCurrentListActivityConsumer.this, OrderCurrentDetailConsumerActivity.class);
		Gson gson =new Gson();
		String jsonString =gson.toJson(mList.get(position));
		intent.putExtra("orderJson", jsonString);
		intent.putExtra("position", position);
		Log.i("info", jsonString);
		startActivityForResult(intent, 1000);;
		
	}
	@Override
	public boolean onItemLongClick(AdapterView<?> parent, View view,
			int position, long id) {
		
		operateDialog(position);
		return true;
	}
	private void operateDialog(final int position) {
        AlertDialog.Builder builder = new AlertDialog.Builder(OrderCurrentListActivityConsumer.this);
        builder.setTitle(mList.get(position).getOrderId());
        builder.setMessage("请选择操作");
        builder.setPositiveButton("取消订单", new DialogInterface.OnClickListener(){
            @Override
            public void onClick(DialogInterface dialog, int which){
            	confirmDialog(position);
            }
        });
        builder.setNegativeButton("更换餐桌", new DialogInterface.OnClickListener(){
            @Override
            public void onClick(DialogInterface dialog, int which){
            	tablePosition=position;
            	Intent intent2 =new Intent(getApplicationContext(), TableSelectActivity.class);
    			intent2.putExtra("bookFlag", true);
    			startActivityForResult(intent2, 1000);
            }
        });
        builder.show();
	}
	private void confirmDialog(final int position) {
        AlertDialog.Builder builder = new AlertDialog.Builder(OrderCurrentListActivityConsumer.this);
        builder.setTitle(mList.get(position).getOrderId()+"");
        builder.setMessage("确认取消吗？");
        builder.setPositiveButton("确认", new DialogInterface.OnClickListener(){
            @Override
            public void onClick(DialogInterface dialog, int which){
            	Util.showTextShort(getApplicationContext(), "正在向店家发起取消订单请求，请稍后...");
            	cancelPosition=position;
            	String url=Constan.BASE_URL+"OrderCurrentCancel";
            	new HttpClientPostThread(url, mHandler, mList.get(position).getOrderId()).start();;
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener(){
            @Override
            public void onClick(DialogInterface dialog, int which){
            	
            }
        });
        builder.show();
	}
	
	private void changeTableDialog(final int position,final String tableName) {
        AlertDialog.Builder builder = new AlertDialog.Builder(OrderCurrentListActivityConsumer.this);
        builder.setTitle(mList.get(position).getOrderId()+"");
        builder.setMessage("确认将餐桌更换为："+tableName+"吗？");
        builder.setPositiveButton("确认", new DialogInterface.OnClickListener(){
            @Override
            public void onClick(DialogInterface dialog, int which){
            	Util.showTextShort(getApplicationContext(), "正在换桌，请稍后...");
//            	tablePosition=position;
            	String url=Constan.BASE_URL+"ChangeTableServlet"+"?orderId="+mList.get(position).getOrderId()+"&tableName="+tableName;
				new HttpClientGetThread(url,mHandler).start();;
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener(){
            @Override
            public void onClick(DialogInterface dialog, int which){
            	tablePosition=-1;
            }
        });
        builder.show();
	}
}
